package com.group3.service.impl;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.group3.dao.*;
import com.group3.domain.*;
import com.group3.exception.BusinessException;
import com.group3.exception.ExceptionEnum;
import com.group3.pojo.WorkRecordInfo;
import com.group3.pojo.receive.WorkReceive;
import com.group3.service.StudentWorkService;
import com.group3.utils.JWTUtils;
import com.group3.utils.NotNull;
import com.group3.utils.Result;
import com.group3.utils.ResultUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * StudentWorkServiceImpl
 *
 * @author HY
 * 2021/06/10 16:54
 **/


@Service
public class StudentWorkServiceImpl implements StudentWorkService {
    @Resource
    private WorkRecordMapper workRecordMapper;
    @Resource
    private TeacherMapper teacherMapper;
    @Resource
    private LessonTeacherMapper lessonTeacherMapper;
    @Resource
    private WorkMapper workMapper;
    @Resource
    private FileMapper fileMapper;
    @Resource
    private StudentWorkMapper studentWorkMapper;
    @Resource
    private GroupStudentMapper groupStudentMapper;

    @Override
    public Result getWork(WorkReceive workReceive) {
        WorkRecordExample recordExample = new WorkRecordExample();
        WorkRecordExample.Criteria criteria = recordExample.createCriteria();
        criteria.andStudentIdEqualTo(workReceive.getStudentId());
        criteria.andStateEqualTo(workReceive.getState());
        if (NotNull.judge(workReceive.getStartTime())) {//传入了发布时间段
            criteria.andReleaseTimeGreaterThanOrEqualTo(workReceive.getStartTime());
        }
        if (NotNull.judge(workReceive.getEndTime())) {//传入了发布时间段
            criteria.andReleaseTimeLessThanOrEqualTo(workReceive.getEndTime());
        }
        if (NotNull.judge(workReceive.getWorkTheme())) {//传入了作业主题
            criteria.andWorkThemeLike("%" + (workReceive.getWorkTheme()) + "%");
        }
        if (NotNull.judge(workReceive.getLessonName())) {//传入了课程（项目）名称
            criteria.andLessonNameEqualTo(workReceive.getLessonName());
        }
        if (NotNull.judge(workReceive.getType())) {//传入了类型
            criteria.andTypeEqualTo(workReceive.getType());
        }
        if (NotNull.judge(workReceive.getTeacherS())) {//传入了实训老师
            LessonTeacherExample lessonTeacherExample = new LessonTeacherExample();
            lessonTeacherExample
                    .createCriteria()
                    .andTeacherIdEqualTo(workReceive.getTeacherS());
            List<LessonTeacherKey> keys = lessonTeacherMapper.selectByExample(lessonTeacherExample);

            if (keys.isEmpty()) {
                return ResultUtil.success();//该老师没有上过课程直接返回
            } else {//该教师有课程
                List<String> lessonNames = new ArrayList<>();
                for (LessonTeacherKey key : keys) {
                    lessonNames.add(key.getLessonName());
                }
                criteria.andLessonNameIn(lessonNames);
            }
        }
        if (NotNull.judge(workReceive.getCompleteTime())) {//传入了完成时间
            criteria.andCompletionTimeLessThanOrEqualTo(workReceive.getCompleteTime());
        }
        PageHelper.startPage(workReceive.getPageNumber(), workReceive.getPageSize());
        List<WorkRecordInfo> workRecords = workRecordMapper.selectWordRecordInfo(recordExample);
        PageInfo<WorkRecordInfo> pageInfo = new PageInfo<>(workRecords);//获取分页信息
        return ResultUtil.success(workRecords, pageInfo.getTotal());
    }

    @Override
    public Result getDetail(Integer workId) {
        Work work = workMapper.selectByPrimaryKey(workId);
        Teacher teacher = teacherMapper.selectByPrimaryKey(work.getTeacherId());

        FileExample fileExample = new FileExample();
        fileExample
                .createCriteria()
                .andOriginTypeEqualTo(0)
                .andOriginIdEqualTo(workId);
        List<File> files = fileMapper.selectByExample(fileExample);
        work.setTeacherName(teacher.getTeacherName());
        work.setFiles(files);

        return ResultUtil.success(work);
    }

    @Override
    @Transactional
    public Result submit(StudentWork submitReceive, String token) {
        DecodedJWT jwt = JWTUtils.getToken(token);//获取token
        String studentId = jwt.getClaim("id").asString();//获取登录学生的id

        submitReceive.setSubmitTime(new Date());
        submitReceive.setStudentId(studentId);//学生id为该登录用户

        StudentWork studentWork = studentWorkMapper.selectByPrimaryKey(submitReceive);
        Work work = workMapper.selectByPrimaryKey(studentWork.getWorkId());
        if (work.getType() >= 1) {//该作业为小组作业
            GroupStudentExample groupStudentExample = new GroupStudentExample();
            groupStudentExample
                    .createCriteria()
                    .andLessonNameEqualTo(work.getLessonName());

            List<GroupStudent> groupStudents
                    = groupStudentMapper.selectByExample(groupStudentExample);

            Integer groupId = null;
            for (GroupStudent groupStudent : groupStudents) {
                if (groupStudent.getGroupLeaderId().equals(studentId)) {
                    groupId = groupStudent.getGroupId();//找出该学生为小组长的小组
                    break;
                }
            }
            if (groupId == null) {//为空就代表学生不为小组长
                throw new BusinessException(ExceptionEnum.NOT_GROUP_LEADER);
            } else {//为小组的所有学生提交作业
                groupStudentExample.clear();
                groupStudentExample
                        .createCriteria()
                        .andGroupIdEqualTo(groupId);
                List<GroupStudent> groupStudents1
                        = groupStudentMapper.selectByExample(groupStudentExample);

                List<String> studentIds = new ArrayList<>();
                for (GroupStudent groupStudent : groupStudents1) {
                    studentIds.add(groupStudent.getStudentId());
                }

                StudentWorkExample studentWorkExample = new StudentWorkExample();
                studentWorkExample
                        .createCriteria()
                        .andWorkIdEqualTo(work.getWorkId())
                        .andStudentIdIn(studentIds);
                submitReceive.setStudentId(null);
                int result = studentWorkMapper
                        .updateByExampleSelective(submitReceive, studentWorkExample);
                if (result == studentIds.size()) {
                    return ResultUtil.success();
                } else if (result >= 0) {
                    return ResultUtil.success("操作成功，但是有成员的作业未找到");
                } else {
                    throw new BusinessException(ExceptionEnum.ERROR);
                }
            }
        } else {//为个人作业
            int result = studentWorkMapper.updateByPrimaryKeySelective(submitReceive);
            if (result > 0) {
                return ResultUtil.success();
            } else {
                throw new BusinessException(ExceptionEnum.ERROR);
            }
        }
    }

    @Override
    public Result getComment(StudentWorkKey studentWorkKey) {
        StudentWork studentWork = studentWorkMapper.selectByPrimaryKey(studentWorkKey);
        return ResultUtil.success(studentWork);
    }

}
